package ru.urfc.portal.developer_tasks;

import junit.framework.JUnit4TestAdapter;
import junit.framework.JUnit4TestAdapterCache;
import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;

import org.junit.internal.runners.JUnit38ClassRunner;
import org.junit.runner.notification.RunNotifier;

public class EjbTestAdapter extends JUnit4TestAdapter {

	private DeveloperTaskService developerTaskService;
	final JUnit4TestAdapterCache fCache = JUnit4TestAdapterCache.getDefault();

	public EjbTestAdapter(Class<?> newTestClass, DeveloperTaskService developerTaskService) {
		super(newTestClass);
		this.developerTaskService = developerTaskService;
	}

	@Override
	public void run(final TestResult result) {
		TestSuite testSuite = initTest(new TestSuite(getTestClass()));
		JUnit38ClassRunner runner = new JUnit38ClassRunner(testSuite);
		RunNotifier notifier = fCache.getNotifier(result, this);
		runner.run(notifier);
	}

	private TestSuite initTest(TestSuite testSuite) {
		for (int i = 0; i < testSuite.testCount(); ++i) {
			Test test = testSuite.testAt(i);
			if (test instanceof BaseTestEjb) {
				developerTaskService.initTest((BaseTestEjb)test);
			} if (test instanceof TestSuite) {
				initTest((TestSuite) test);
			}
		}
		return testSuite;
	}

}